package com.tangtang.register.server;

public class RegisterServiceController {

    private Registry registry = Registry.getInstance();

    public RegisterResponse register(RegisterRequest request) {
        RegisterResponse response = new RegisterResponse();

        try {
            ServiceInstance serviceInstance = new ServiceInstance();
            serviceInstance.setServiceInstenceId(request.getServiceInstenceId());
            serviceInstance.setHostName(request.getHostName());
            serviceInstance.setIp(request.getIp());
            serviceInstance.setPort(request.getPort());
            serviceInstance.setServerName(request.getServerName());

            serviceInstance.setLease(new ServiceInstance.Lease());

            registry.register(serviceInstance);

            response.setStatus(RegisterResponse.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(RegisterResponse.FAILURE);
        }
        return response;
    }

    public HeartbeatResponce heartbeat(HeartbeatRequest request) {
        HeartbeatResponce responce = new HeartbeatResponce();
        try {
            ServiceInstance serviceInstance = Registry.getInstance().getServiceInstance(request.getServerName()
                    , request.getServiceInstanceId());
            serviceInstance.getLease().renew();
            responce.setStatus(HeartbeatResponce.SUCCESS);
            responce.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            responce.setStatus(HeartbeatResponce.FAILURE);
        }
        return responce;
    }

}
